<template>
  <div class="notification-container">
    <!-- 操作功能区 -->
    <div class="action-bar">
      <button @click="markAllAsRead" class="mark-read-btn">
        标记全部已读
      </button>
       <span class="unread-count">共{{ categoryStats.all.total }}条消息，其中未读消息{{ categoryStats.all.unread_count }}条</span>
    </div>

    <!-- 分类筛选 -->
    <div class="category-filter">
      <button
          v-for="category in categories"
          :key="category.value"
          @click="handleCategoryChange(category.value)"
          :class="{ active: selectedCategory === category.value }"
      >
        {{ category.label }}
          <span class="category-count">
        ({{ categoryStats[category.value].unread_count }}/{{ categoryStats[category.value].total }})
      </span>
        <span v-if="category.verbs" class="category-tip">
      ({{ category.verbs.length }}种类型)
    </span>
      </button>

      <!-- 合并互动类型下拉菜单 -->
      <select
          v-if="selectedCategory === 'interaction'"
          v-model="selectedVerb"
          @change="handleVerbChange"
          class="verb-select"
      >
        <option value="">所有互动类型</option>
        <option
            v-for="verb in interactionVerbs"
            :key="verb"
            :value="verb"
        >
          {{ typeLabels[verb] }}
        </option>
      </select>

    </div>



    <!-- 加载状态 -->
    <div v-if="loading" class="loading">加载中...</div>

    <!-- 错误提示 -->
    <div v-if="error" class="error">{{ error }}</div>

    <!-- 通知列表 -->
    <div class="notification-list">
      <div
          v-for="notification in notifications"
          :key="notification.id"
          class="notification-item"
          :class="{
          unread: notification.status === 'unread',
          'system-notification': notification.verb === 'system'
        }"
          @click="handleItemClick(notification)"
      >
         <!-- 新增已读标记按钮 -->
  <div class="read-indicator" @click.stop="handleItemClick(notification)">
    <span v-if="notification.status === 'unread'" class="unread-dot"></span>
    <span v-else class="read-check">✓</span>
  </div>
        <!-- 系统通知图标 -->
        <div class="notification-content">
          <!-- 头部信息 -->
          <div class="notification-header">
          <span
              class="type-tag"
              :style="{
      backgroundColor: typeColors[notification.verb],
      color: 'white'
    }"
          >
    {{ typeLabels[notification.verb] }}
  </span>
            <div class="meta-info">
              <template v-if="notification.sender">
                <span class="sender" v-if="notification.sender.nickname">来自：{{ notification.sender.nickname }}</span>
              </template>
              <div v-if="notification.verb === 'system' && notification.system_level" class="system-level">
                优先级：{{ systemLevelLabels[notification.system_level] }}
              </div>
              <span class="time">{{ formatTime(notification.timestamp) }}</span>
            </div>
          </div>

          <!-- 通知内容 -->
          <div class="content-wrapper">
            <h3 class="title">{{ notification.title }}</h3>
            <p class="content">{{ notification.content }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页控件 -->
    <div class="pagination" v-if="pageCount > 1">
      <button
          v-for="page in pageCount"
          :key="page"
          @click="changePage(page)"
          :class="{ active: currentPage === page }"
          :disabled="loading"
      >
        {{ page }}
      </button>
    </div>
  </div>
</template>

<script setup>
import {useUserStore} from "@stores/userStore.js";

const store = useUserStore()


// 响应式数据
const notifications = ref([])
const unreadCount = ref(0)
const allCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(15)
const pageCount = ref(1)
const loading = ref(false)
const error = ref(null)
const showDropdown = ref(false);
const categoryStats = ref({
  all: { total: 0, unread_count: 0 },
  system: { total: 0, unread_count: 0 },
  interaction: { total: 0, unread_count: 0 },
  message: { total: 0, unread_count: 0 }
})
const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value;
};

const handleVerbClick = (verb) => {
  selectedVerb.value = verb;
  fetchData(); // 更新数据
  showDropdown.value = false; // 关闭下拉菜单
};

const dropdownLabel = computed(() => {
  const categoryVerbs = selectedVerb.value ? selectedVerb.value : '所有互动类型';
  return `互动提醒 (${categoryVerbs})`;
});

// 分类配置
const interactionVerbs = ['comment', 'reply', 'like', 'follow', 'collect', 'mention']

const categories = ref([
  {value: 'all', label: '全部'},
  {value: 'system', label: '系统通知'},
  {value: 'message', label: '私信'},
  {
    value: 'interaction',
    label: '互动提醒',
    verbs: interactionVerbs // 明确关联的verb类型
  }
])

const selectedCategory = ref('all')
const selectedVerb = ref('')

const handleVerbChange = () => {
  currentPage.value = 1
  fetchData()
}

// 类型映射
const typeLabels = {
  system: '系统',
  message: '私信',
  comment: '评论',
  reply: '回复',
  like: '点赞',
  follow: '关注',
  collect: '收藏',
  mention: '@提及'
}
// 类型颜色映射
const typeColors = {
  system: '#67c23a',
  message: '#409eff',
  comment: '#e6a23c',
  reply: '#f56c6c',
  like: '#9c27b0',
  follow: '#ff9800',
  collect: '#4caf50',
  mention: '#2196f3'
}

const systemLevelLabels = {
  urgent: '紧急',
  normal: '普通'
}

// 初始化获取数据
const fetchData = async () => {
  try {
    loading.value = true
    error.value = null

    // 获取通知列表
    const params = {
      page: currentPage.value,
      page_size: pageSize.value
    }

    if (selectedCategory.value !== 'all') {
      const categoryConfig = categories.value.find(c => c.value === selectedCategory.value)
      if (categoryConfig.verbs) {
        params.verb = selectedVerb.value || categoryConfig.verbs.join(',')
      } else {
        params.verb = selectedCategory.value
      }
    }


    const [notifRes, countRes, statsRes] = await Promise.all([
      axios.get('/api/comments/notifications/', {params},{ requiresAuth: true }),
      axios.get('/api/comments/notifications/unread_count/', { requiresAuth: true }),
      axios.get('/api/comments/notifications/category_counts/', { requiresAuth: true })
    ])

    notifications.value = notifRes.data.results
    pageCount.value = notifRes.data.total_pages || Math.ceil(notifRes.data.count / pageSize.value)
    unreadCount.value = countRes.data.count
    allCount.value = notifRes.data.count
    categoryStats.value = statsRes.data
  } catch (err) {
    error.value = err.response?.data?.message || '数据加载失败'
  } finally {
    loading.value = false
  }
}

// 分页切换
const changePage = (page) => {
  currentPage.value = page
  window.scrollTo({ top: 0, behavior: 'smooth' }) // 新增滚动逻辑
  fetchData()
}


// 分类切换
const handleCategoryChange = (category) => {
  currentPage.value = 1
  selectedCategory.value = category
  selectedVerb.value = '';
  fetchData()
}

// 时间格式化
const formatTime = (timestamp) => {
  if (!timestamp) return '时间不可用';

  const date = new Date(timestamp); // 确保 timestamp 是 Unix 时间戳
  if (isNaN(date.getTime())) return '时间格式错误';

  const now = Date.now();
  const diff = now - date.getTime();

  const minute = 60 * 1000;
  const hour = 60 * minute;
  const day = 24 * hour;
  const month = 30 * day;
  const year = 365 * day;

  if (diff < minute) {
    return `${Math.floor(diff / 1000)}秒前`;
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`;
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`;
  } else if (diff < month) {
    return `${Math.floor(diff / day)}天前`;
  } else if (diff < year) {
    return `${Math.floor(diff / month)}个月前`;
  } else {
    return `${Math.floor(diff / year)}年前`;
  }
};


// 标记单个为已读
const handleItemClick = async (notification) => {
  if (notification.status === 'unread') {
    try {
      await axios.patch(`/api/comments/notifications/${notification.id}/`, {
        status: 'read'
      }, { requiresAuth: true })
      notification.status = 'read'
      unreadCount.value = Math.max(0, unreadCount.value - 1)

      // 根据verb判断分类
      const getCategory = (verb) => {
        if (verb === 'system') return 'system'
        if (verb === 'message') return 'message'
        return 'interaction' // 其他都归为互动类
      }

      const category = getCategory(notification.verb)
      categoryStats.value[category].unread_count--
      categoryStats.value.all.unread_count--
    } catch (err) {
      console.error('标记已读失败:', err)
    }
  }
}


// 标记全部已读
const markAllAsRead = async () => {
  try {
    const {data} = await axios.patch('/api/comments/notifications/mark_all_as_read/',{ requiresAuth: true })
    notifications.value.forEach(n => n.status = 'read')
    unreadCount.value = 0
     Object.values(categoryStats.value).forEach(stat => {
    stat.unread_count = 0
  })
  } catch (err) {
    error.value = '标记已读操作失败'
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
/* 基础容器 */
.notification-container {
  max-width: 800px;
  margin: 40px auto;
  padding: 20px;
  border-radius: 8px;
}
/* 新增已读标记样式 */
.read-indicator {
  position: relative;
  min-width: 32px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.unread-dot {
  display: block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #f56c6c;
  animation: pulse 1.5s infinite;
}

.read-check {
  color: #67c23a;
  font-weight: bold;
  font-size: 1.2em;
}

@keyframes pulse {
  0% { transform: scale(0.95); }
  50% { transform: scale(1.1); }
  100% { transform: scale(0.95); }
}

/* 调整通知项布局 */
.notification-item {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  position: relative;
}

/* 调整操作栏样式：让标记已读按钮和未读数量合理布局 */
.action-bar {
  display: flex;
  align-items: center; /* 垂直居中 */
  margin-bottom: 20px;
}

.action-bar .mark-read-btn {
  padding: 8px 16px;
  font-size: 14px;
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s, opacity 0.3s;

  &:hover {
    background: #66b1ff; /* hover 效果 */
    opacity: 0.9;
  }
}

.action-bar .unread-count {
  font-size: 14px;
  color: #909399;
  margin-left: 16px;
}


.action-bar .mark-read-btn:hover {
  background: #66b1ff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.5);
}

.interaction-wrapper button {
  padding: 8px 16px;
  border-radius: 20px;
  border: 1px solid #409eff;
  background: #409eff;
  color: white;
  cursor: pointer;
  transition: background 0.3s;
}

.interaction-wrapper button:hover {
  background: #66b1ff;
}

.interaction-dropdown li {
  padding: 8px 12px;
  cursor: pointer;
  transition: background 0.3s;
}

.interaction-dropdown li:hover {
  background: #f2f6fc;
}

.interaction-menu button {
  width: 100%;
  padding: 8px 12px;
  text-align: left;
  border: none;
  background: none;
  cursor: pointer;
}

.interaction-menu button:hover {
  background: #409eff;
  color: white;
}

/* 分类筛选 */
.category-filter {
  margin: 20px 0;
  display: flex;
  gap: 12px;
.category-count {
  margin: 0 4px;
  color: #666;
  font-size: 0.9em;
}
.category-count::before {
  content: "📊";
  margin-right: 2px;
}
  button {
    padding: 8px 16px;
    border: 1px solid #e0e0e0;
    border-radius: 16px;
    background: #fff;
    transition: all 0.3s;

    &:hover {
      background: #f5f7fa;
      border-color: #409eff;
    }

    &.active {
      background: #409eff;
      color: white;
      border-color: #409eff;
    }
  }

  .category-tip {
    font-size: 0.8em;
    opacity: 0.7;
  }
}
.verb-select {
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: #fff;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: #f5f7fa;
  }
}


/* 通知列表 */
.notification-list {
  margin-top: 16px;
  background: #fff;
  border-radius: 4px;

  .notification-item {
    padding: 16px;
    border-bottom: 1px solid #e0e0e0;
    transition: background 0.2s;
    cursor: pointer;
    display: flex;
    align-items: flex-start;

    &.unread {
      background: #f8fbff;
    }

    &:hover {
      background: #f5f7fa;
    }
  }
}

/* 通知内容区域 */
.title {
  margin: 8px 0;
  font-size: 16px;
  color: #333;
}
.notification-content {
  flex-grow: 1;
  font-size: 14px;
  line-height: 1.5;
  color: #666;

  .notification-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    .meta-info {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      font-size: 0.85em;

      .sender {
        color: #409eff;
      }

      .time {
        color: #909399;
      }
    }
  }
}

/* 类型标签 */
.type-tag {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}


/* 系统通知特殊样式 */
.system-notification {
  border-left: 3px solid #5FB878;

  &[system_level="urgent"] {
    border-color: #f56c6c;
  }

  &[system_level="normal"] {
    border-color: #67c23a;
  }

  .system-level {
    color: #f56c6c;
    font-weight: 600;
    margin-bottom: 8px;
  }
}

/* 分页样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  gap: 8px;
  justify-content: center;

  button {
    padding: 6px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;

    &.active {
      background: #409eff;
      color: white;
      border-color: #409eff;
    }
  }
}
.pagination button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}


/* 辅助样式 */
.loading, .error {
  text-align: center;
  padding: 20px;
  font-size: 1.1em;

  &.error {
    color: #f56c6c;
  }

  &.loading {
    color: #909399;
  }
}

.time {
  font-size: 0.85em;
  color: #888;
  font-family: monospace; /* 保持数字对齐 */
  min-width: 96px; /* 固定宽度防止抖动 */
  display: inline-block;
  text-align: right;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .meta-info {
    flex-direction: column;
    align-items: flex-start !important;
  }

  .time {
    font-size: 0.75em;
    margin-top: 4px;
  }
}
</style>